﻿using System;
using System.Linq;
using System.Web.Mvc;
using IT.CMS.Web.Areas.Administration.Models.Sites;
using IT.CMS.Core.Domain.Sites;
using IT.CMS.Services.Localization;
using IT.CMS.Services.Security;
using IT.CMS.Services.Sites;
using IT.CMS.Web.Framework.Controllers;
using Telerik.Web.Mvc;

namespace IT.CMS.Web.Areas.Administration.Controllers
{
    [AdminAuthorize]
    public partial class SiteController : BaseCmsController
    {
        private readonly ISiteService _siteService;
        private readonly ILocalizationService _localizationService;
        private readonly IPermissionService _permissionService;

        public SiteController(ISiteService siteService,
            ILocalizationService localizationService,
            IPermissionService permissionService)
        {
            this._siteService = siteService;
            this._localizationService = localizationService;
            this._permissionService = permissionService;
        }

        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSites))
                return AccessDeniedView();

            return View();
        }

        [HttpPost, GridAction(EnableCustomBinding = true)]
        public ActionResult List(GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSites))
                return AccessDeniedView();

            var siteModels = _siteService.GetAllSites()
                .Select(x => x.ToModel())
                .ToList();

            var gridModel = new GridModel<SiteModel>
            {
                Data = siteModels,
                Total = siteModels.Count()
            };

            return new JsonResult
            {
                Data = gridModel
            };
        }

        public ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSites))
                return AccessDeniedView();

            var model = new SiteModel();
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormNameAttribute("save-continue", "continueEditing")]
        public ActionResult Create(SiteModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSites))
                return AccessDeniedView();
            
            if (ModelState.IsValid)
            {
                var site = model.ToEntity();
                //ensure we have "/" at the end
                if (!site.Url.EndsWith("/"))
                    site.Url += "/";
                _siteService.InsertSite(site);

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Sites.Added"));
                return continueEditing ? RedirectToAction("Edit", new { id = site.Id }) : RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSites))
                return AccessDeniedView();

            var site = _siteService.GetSiteById(id);
            if (site == null)
                //No site found with the specified id
                return RedirectToAction("List");

            var model = site.ToModel();
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormNameAttribute("save-continue", "continueEditing")]
        [FormValueRequired("save", "save-continue")]
        public ActionResult Edit(SiteModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSites))
                return AccessDeniedView();

            var site = _siteService.GetSiteById(model.Id);
            if (site == null)
                //No site found with the specified id
                return RedirectToAction("List");
            
            if (ModelState.IsValid)
            {
                site = model.ToEntity(site);
                //ensure we have "/" at the end
                if (!site.Url.EndsWith("/"))
                    site.Url += "/";
                _siteService.UpdateSite(site);

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Sites.Updated"));
                return continueEditing ? RedirectToAction("Edit", new { id = site.Id }) : RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSites))
                return AccessDeniedView();

            var site = _siteService.GetSiteById(id);
            if (site == null)
                //No site found with the specified id
                return RedirectToAction("List");

            try
            {
                _siteService.DeleteSite(site);
                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Sites.Deleted"));
                return RedirectToAction("List");
            }
            catch (Exception exc)
            {
                ErrorNotification(exc);
                return RedirectToAction("Edit", new {id = site.Id});
            }
        }
    }
}
